package com.ljq.rpc.client.handler;


import com.alibaba.fastjson.JSONObject;
import com.ljq.rpc.client.utils.FutureFactory;
import com.ljq.rpc.common.enums.MsgType;
import com.ljq.rpc.common.pojo.Request;
import com.ljq.rpc.common.pojo.Response;
import com.ljq.rpc.common.pojo.RpcFuture;
import com.ljq.rpc.common.protocol.dubboProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyClientHandler extends SimpleChannelInboundHandler<dubboProtocol> {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与服务器连接成功");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, dubboProtocol msg) throws Exception {
        Response response = JSONObject.parseObject(msg.getContent().toString(), Response.class);
        Long request_id = JSONObject.parseObject(msg.getREQUEST_ID().toString(), Long.class);
        RpcFuture future = FutureFactory.get(request_id);
        future.getPromise().setSuccess(response);
        FutureFactory.remove(request_id);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
